package org.ucas.faker.web.aop;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.ucas.faker.web.annotation.Registry;
import org.ucas.faker.web.dao.ApplicationDao;
import org.ucas.faker.web.entity.Application;
import org.ucas.faker.web.exceptions.AppNotImplemented;

import java.lang.annotation.Annotation;

/**
 * Created by suemi on 17-7-7.
 */
@Aspect
@Component
public class RegistryAspect {
  private static Logger logger = LogManager.getLogger(RegistryAspect.class);

  @Autowired
  private ApplicationDao applicationDao;

  @Pointcut("@annotation(org.ucas.faker.web.annotation.Registry)")
  public void controllerAspect() {}

  @Before("controllerAspect()")
  public void doBefore(JoinPoint point) throws NoSuchMethodException {
    MethodSignature signature = (MethodSignature) point.getSignature();
    String methodName = signature.getMethod().getName();
    Class<?>[] parameterTypes = signature.getMethod().getParameterTypes();
//    Annotation[][] annotations = point.getTarget().getClass().getMethod(methodName,parameterTypes).getParameterAnnotations();

    Registry registry = point.getTarget().getClass().getMethod(methodName,parameterTypes).getDeclaredAnnotation(Registry.class);
    if(registry != null) {
      final Application app = applicationDao.findOne(registry.code());
      if(app == null || !app.getStatus().equals(Application.Status.ONLINE))
        throw new AppNotImplemented("Application "+registry.code()+"can't be accessed now!");
    }
  }
}
